package com.ssms.service;

import com.ssms.commons.Result;
import com.ssms.commons.TablePage;
import com.ssms.dao.NoticeMapper;
import com.ssms.model.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NoticeService {

    @Resource
    private NoticeMapper noticeMapper;

    public TablePage search(TablePage tablePage, Integer userId) {
        int size = tablePage.getLimit();
        int start = (tablePage.getPage() - 1) * size;
        // 获取分页数据
        List<Notice> list = noticeMapper.selectPage(start, size, userId);
        // 获取符合条件的总数
        int count = noticeMapper.selectPageCount(userId);
        tablePage.setCount(count);
        tablePage.setData(list);

        List<Notice> notices = list.stream().filter(notice -> notice.getStatus() == 0).collect(Collectors.toList());
        for (Notice notice : notices) {
            notice.setStatus(1); // 查询后就设置为已读状态
            update(notice);
        }
        return tablePage;
    }


    public Result update(Notice notice) {
        int count = noticeMapper.updateByPrimaryKeySelective(notice);
        return count > 0?Result.success():Result.failed("更新失败", 500);
    }


    public Result getCount(Integer userId) {
        return Result.success(noticeMapper.selectCount(userId));
    }
}
